from django.shortcuts import render

# Create your views here.
from rest_framework import viewsets
from rest_framework import mixins
from rest_framework.permissions import IsAuthenticated

from .models import UserFav, UserLeavingMessage, UserAddress
from .permissions import IsOwnerOrReadOnly
from .serializers import UserFavSerializer, UserFavDetailSerializer, LeavingMessageSerializer, AddressSerializer


# Create your views here.


class UserFavViewset(mixins.ListModelMixin,mixins.CreateModelMixin,mixins.RetrieveModelMixin,
                     mixins.DestroyModelMixin,viewsets.GenericViewSet):
    '''
    用户收藏功能 CreateModelMixin是搞添加收藏，DestroyModelMixin是搞删除收藏
    '''
    # queryset = UserFav.objects.all()  #查询数据集合，任何类都要拿数据才能操作
    # serializer_class = UserFavSerializer #序列化类
    permission_classes = (IsAuthenticated,IsOwnerOrReadOnly)
    lookup_field = "goods_id"
    def get_queryset(self):
        """
        让每个人只看到自己的收藏
        :return:
        """
        return UserFav.objects.filter(user=self.request.user)

    def get_serializer_class(self):
        if self.action == "list":
            return UserFavDetailSerializer
        elif self.action == "create":
            return UserFavSerializer

        return UserFavSerializer

    def perform_create(self, serializer):
        instance = serializer.save()#得到serializer
        goods = instance.goods
        goods.fav_num += 1#对收藏数加1
        goods.save()

    def perform_destroy(self, instance):
        goods = instance.goods
        goods.fav_num -= 1#对收藏数减1
        goods.save()
        instance.delete()

class LeavingMessageViewset(mixins.ListModelMixin, mixins.DestroyModelMixin,
                            mixins.CreateModelMixin,viewsets.GenericViewSet):
    """
    list:
        获取用户留言
    create:
        添加留言
    delete:
        删除留言功能
    """

    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
    # authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = LeavingMessageSerializer

    def get_queryset(self):
        return UserLeavingMessage.objects.filter(user=self.request.user)


class AddressViewset(viewsets.ModelViewSet):
    """
    收货地址管理
    list:
        获取收货地址
    create:
        添加收货地址
    update:
        更新收货地址
    delete:
        删除收货地址
    """
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
    serializer_class = AddressSerializer

    def get_queryset(self):
        """
        每个用户只能看到自己的地址列表
        :return:
        """
        return UserAddress.objects.filter(user=self.request.user)